from django.shortcuts import render
from rest_framework import status
from rest_framework.views import APIView
from django.conf import settings
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
import logging
from rest_framework_jwt.settings import api_settings

from QQLoginTool.QQtool import OAuthQQ

from .utils import generate_save_user_token
from .models import OAuthQQUser
from .serializers import QQAuthUserSerializer


logger = logging.getLogger('django')

# Create your views here.


# url: /oauth/qq/authorization/?next=xxx
class QQAuthURLView(APIView):
    """生成QQ扫码url"""
    def get(self, request):

        # next 表示从哪个页面进入到的登录页面，将来登录成功后，就自动跳转到哪个页面
        next = request.query_params.get("next")
        if not next:
            next = '/'

        # 获取QQ登录页面的url，因为需要根据开发者配置生成不同的二维码页面
        oauth = OAuthQQ(settings.QQ_CLIENT_ID,
                        settings.QQ_CLIENT_SECRET,
                        settings.QQ_REDIRECT_URI,
                        state=next)
        login_url = oauth.get_qq_url()

        return Response(data={'login_url': login_url})


class QQAuthUserView(GenericAPIView):
    """用户扫码登录成功后的回调处理"""

    # 指定序列化器
    serializer_class = QQAuthUserSerializer

    def get(self, request):
        """code请求"""
        code = request.query_params.get('code')
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)

        # 创建OAuthQQ对象
        oauth = OAuthQQ(settings.QQ_CLIENT_ID,
                        settings.QQ_CLIENT_SECRET,
                        settings.QQ_REDIRECT_URI,
                        state=next)
        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)
            # 使用access_token请求openid
            openid = oauth.get_open_id(access_token)
        except Exception as error:
            logger.error(error)
            return Response({"message": error}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 拿到openid后，查询该QQ用户是否是美多商城的注册用户
        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城用户，创建用户并绑定openid
            # 为了能够在后续的绑定用户操作中前端可以使用openid,在这里将openid签名后响应给前段
            access_token_openid = generate_save_user_token(openid)
            return Response(data={"access_token": access_token_openid})
        else:
            # 如果openid已绑定美多商城用户，那么直接生成JWT_token,并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 根据外键得到user
            user = oauth_user.user
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })

            return response

    def post(self, request):
        """openid绑定到用户"""

        # 获取序列化对象
        serializer = self.get_serializer(data=request.data)
        # 开启校验
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 生成JWT token, 并且响应
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        response = Response(data={
            'token': token,
            'user_id': user.id,
            'username': user.username
        })

        return response
